<template>
    <el-dialog :title="Id == undefined ? '新增' : '修改'" :visible.sync="deitOpen" width="60%"
        :before-close="closeDelDialog" :modal-append-to-body="false">

        <el-form ref="addForm" :model="addForm" :rules="rules" label-width="140px" style="margin:20px 20px 0">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="档案门类" prop="categoryId">
                        <treeselect v-model="addForm.categoryId" :options="options" :disable-branch-nodes="true" label
                            placeholder="请选择档案门类" noOptionsText="暂无数据"
                            :normalizer="normalizerCategoryID"
                            :style="isStyle ? 'line-height: 32px;font-size:12px' : 'line-height: 36px;font-size:14px'" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="数据包名称" prop="name">
                        <el-input v-model="addForm.name" placeholder="请输入数据包名称" readonly></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="大小" prop="size">
                        <el-input v-model="size" placeholder="请输入大小" readonly></el-input>
                    </el-form-item>
                </el-col>


                <el-col :span="12">
                    <el-form-item label="格式" prop="format">
                        <el-input v-model="addForm.format" placeholder="请输入格式" readonly></el-input>
                    </el-form-item>
                </el-col>

            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="保存时间（年）" prop="saveTime">
                        <el-select v-model="addForm.saveTime" placeholder="请选择" clearable style="width: 100%">
                            <el-option v-for="(item, index) in dict.type.BGQX" :key="index" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="保存日期" prop="receivingTime">
                        <el-date-picker v-model="addForm.receivingTime" type="datetime" placeholder="请输入保存日期"
                            style="width:100%" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="Id != undefined">
                <el-col :span="12">
                    <el-form-item label="是否通过检测" prop="textdetile">
                        <el-input v-model="textdetile" placeholder="请输入是否通过检测" readonly></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="存储路径" prop="path">
                        <el-input v-model="addForm.path" placeholder="请输入存储路径" readonly></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="备注" >
                        <el-input v-model="addForm.remark" type="textarea" placeholder="请输入备注"></el-input>
                    </el-form-item>
                </el-col>

            </el-row>
            <el-row v-if="Id == undefined">
                <el-col :span="12">

                    <el-form-item label="上传文件" prop="file">
                        <el-upload :on-change="handleChange" drag :auto-upload="false" :fileList="fileListData" action="/"
                            :limit="1">
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        </el-upload>


                    </el-form-item>
                </el-col>

            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm('addForm')">保 存</el-button>
            <el-button @click="closeDelDialog">取 消</el-button>
        </div>



    </el-dialog>
</template>
<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getcatetreesList } from "@/api/cqbc/all.js"
import { handadd, getDataManagebyId, update } from "@/api/cqbc/dataManage/receiveDetection.js"
export default {
    archive_Dicts: ['BGQX'],
    watch: {
        Id: {
            handler(val) {
                if (val != undefined) { //修改
                    getDataManagebyId(val).then(res => {
                        this.addForm = res.data;
                        this.addForm.categoryId = res.data.category
                        if (res.data.sixingDetail == "200") {
                            this.textdetile = "已通过"
                        } else if (res.data.sixingDetail == "400") {
                            this.textdetile = "未通过"
                        } else {
                            this.textdetile = "未检测"
                        }
                        this.size = this.changeType(res.data.size);
                    })


                    this.rules["file"] = []

                }
            },
            immediate: true
        }
    },
    props: ["deitOpen", "Id"],
    components: {
        Treeselect
    },
    data() {
        return {
            size: undefined,
            isStyle:false,
            addForm: {
                categoryId: undefined,
                name: undefined,
                receivingTime: undefined,
                format: undefined,
                saveTime: undefined,
                remark: undefined,
                size: undefined,
                file: undefined
            },
            rules: {
                categoryId: [
                    { required: true, message: "请选择门类", trigger: "blur" }
                ],

                receivingTime: [
                    { required: true, message: "请选择保存时间", trigger: "blur" }
                ],
                saveTime: [
                    { required: true, message: "请选择保存时间（年）", trigger: "blur" }
                ],
                file: [
                    { required: true, message: "请上传文件", trigger: "blur" }
                ],

            },
            options: [],
            fileListData: [],
            textdetile: undefined,


        }
    },
    filters: {

    },
    created() {
        if (this.$store.getters.size == 'small') {

            this.isStyle = true

        } else {

            this.isStyle = false
        }
        this.categorylistPOST(); //档案门类树列表
        this.addForm.receivingTime = this.getNowTime(1);

    },
    methods: {
        selectNode(node) {
            console.log(node, "sdfjlsdkfjsklj")

        },
        changeType(val) {
            if (val != undefined) {
                if (val == "0") return "0B";
                var k = 1024;
                var sizes = ["B", "KB", "MB", "GB", "TB"];
                // console.log('Math.log(val)', Math.log(val));
                // console.log('Math.log(k)', Math.log(k));
                let i = Math.floor(Math.log(val) / Math.log(k));//得出该数字的单位应该是kB?MB
                let convertedVal = (val / Math.pow(k, i)).toPrecision(3);
                if (convertedVal.includes("e")) {
                    convertedVal = parseFloat(convertedVal).toFixed(0);
                }
                // console.log(i, convertedVal + sizes[i]);
                return convertedVal + sizes[i];
            }
        },
        // 只能选择数据下面有children 的数据，没有children的时候禁用
        normalizerCategoryID(node) {
            if (node.nodeType == 'fonds') {
                if (node.children == undefined || node.children == null || !node.children.length) {

                    node['isDisabled'] = true;
                }

            }
            if (node.children == null || node.children == undefined || !node.children.length) {
                delete node.children;
            }
            return node
        },
        getFileNameWithoutExtension(filePath) {
            // 使用split分割字符串，以"."为分隔符
            var parts = filePath.split('.');
            // 获取除了扩展名之外的文件名部分
            var fileNameWithoutExtension = parts.slice(0, -1).join('.');
            return fileNameWithoutExtension;
        },
        handleChange(file, fileList) {
            var that = this;
            if (file.status !== "ready") return;
            let suffName = file.name.substring(file.name.lastIndexOf('.') + 1)
            const extension = suffName === 'zip'
            const extension2 = suffName === 'zip'
            // const isLt10M = file.size / 1024 / 1024 < 10
            if (!extension && !extension2) {
                that.$message({
                    message: '上传文件只能是 .zip格式!',
                    type: 'warning'
                })
                that.fileListData = [];
            } else {

                that.fileListData = [file];

                that.size = that.changeType(that.fileListData[0].size);
                that.addForm.size = that.fileListData[0].size;
                console.log(that.fileListData[0].name.length)
                that.addForm.name = that.getFileNameWithoutExtension(that.fileListData[0].name);
                this.addForm.file = that.fileListData[0].raw
                that.addForm.format = "zip"

            }


            return true;
        },
        // //档案门类树列表
        categorylistPOST() {
            getcatetreesList().then(response => {
                this.options = response.data;
            });

        },
        closeDelDialog() {
            this.$emit("closeDelDialog")
        },
        submitForm(addForm) {
            this.$refs[addForm].validate((valid) => {
                const formData = new FormData();
                if (valid) {
                    formData.append("category", this.addForm.categoryId);
                    formData.append("file", this.addForm.file);
                    formData.append("format", this.addForm.format);
                    formData.append("name", this.addForm.name);
                    formData.append("receivingTime", this.addForm.receivingTime);
                    console.log(this.addForm.remark,"beizu ")

                    if (this.addForm.remark != undefined) {
                        formData.append("remark", this.addForm.remark);
                    }
                    formData.append("saveTime", this.addForm.saveTime);
                    formData.append("size", this.addForm.size);
                    if (this.Id == undefined) {
                        handadd(formData).then(res => {
                            if (res.code == "200") {
                                this.$modal.msgSuccess("添加成功");
                                this.$emit("addsubmitForm")
                            }
                        })
                    } else {
                        update(this.addForm).then(res => {
                            if (res.code == "200") {
                                this.$modal.msgSuccess("修改成功");
                                this.$emit("addsubmitForm")
                            }
                        })

                    }

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },


    }
}

</script>
<style lang="scss" scoped>
::v-deep .el-dialog {
    display: flex;
    flex-direction: column;
    margin: 0 !important;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    max-height: calc(100% - 30px);
    max-width: calc(100% - 30px);
}

::v-deep .el-dialog .el-dialog__body {
    flex: 1;
    overflow: auto;
}
</style>

